﻿using System;
using System.Linq;
using System.Web.Mvc;
using Backend.JYD.BLL.Cust;
using Backend.JYD.BLL.Task;
using Backend.JYD.RunTime;
using Backend.JYD.Model.Cust;
using Backend.JYD.Model.Task;
using Backend.JYD.Common;
using Backend.JYD.Business;
using System.Collections.Generic;
using Backend.JYD.BLL;

namespace Backend.JYD.Web.Controllers
{
    public class IntentController : BaseController
    {
        //ViewBag.CurrMenu = "mu01";
        private IntentEntryInfoBLL bll = new IntentEntryInfoBLL();
        private CustBaseBLL bllCust = new CustBaseBLL();
        private CustManager manager = new CustManager();

        public ActionResult Index(int? page, DateTime? start, DateTime? end, int? status, string custNo)
        {
            if (!page.HasValue || page <= 0) page = 1;
            if (!status.HasValue || status <= -1) status = -1;

            #region Pager

            string url = "/intent/index?page={0}";
            if (start.HasValue)
            {
                this.ViewBag.StartDate = DateTimeHelper.GetDateShortFormat(start.Value);
                url += "&start=" + DateTimeHelper.GetDateShortFormat(start.Value);
            }
            if (end.HasValue)
            {
                this.ViewBag.EndDate = DateTimeHelper.GetDateShortFormat(end.Value);
                url += "&end=" + DateTimeHelper.GetDateShortFormat(end.Value);
            }
            this.ViewBag.Status = -1;
            if (status > -1)
            {
                this.ViewBag.Status = status;
                url += "&status=" + status;
            }

            this.ViewBag.PageUrl = url;

            #endregion

            var list = bll.GetIntentEntryInfoByPage(this.EmpId, start, end, status.Value, new Model.PageInfo() { PageIndex = page.Value, PageSize = BaseController.PageSize20 });
            if (list != null && list.PageList != null)
            {
                this.ViewBag.PageIndex = list.PageIndex;
                this.ViewBag.PageSize = list.PageSize;
                this.ViewBag.PageCount = list.PageCount;
                this.ViewBag.ItemCount = list.ItemCount;

                List<Int64> ids = list.PageList.ConvertAll<Int64>(p => p.OpId.HasValue ? p.OpId.Value : 0);
                ids.RemoveAll(p => p <= 0);
                ids = ids.Distinct().ToList();
                this.ViewBag.EmpInfos = new EmpInfoBLL().GetEmpInfoByEmpIds(ids, true);

                return View(list.PageList);
            }

            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(IntentEntryInfo info, FormCollection collection)
        {
            #region IntentEntryInfo
            if (string.IsNullOrEmpty(info.CustName))
            {
                this.ViewBag.Msg = "请输入客户姓名、称呼";
                return View(info);
            }
            if (string.IsNullOrEmpty(info.Phone))
            {
                this.ViewBag.Msg = "请输入客户电话";
                return View(info);
            }
            if (!CommonHelper.CheckPaperNo(info.PaperNo))
            {
                this.ViewBag.Msg = "请输入有效的身份证号";
                return View(info);
            }

            #endregion
            try
            {
                info.CreateTime = DateTime.Now;
                info.UpdateTime = DateTime.Now;
                info.OpId = this.EmpId;
                info.Type = 1;
                info.Status = 0;
                Int64 intentId = bll.AddIntentEntryInfo(info);
                info.IntentId = intentId;
                bool success = info.IntentId > 0;
                if (!success)
                {
                    //return View("Error");
                    return Json(new { code = false, msg = "保存失败。" }, JsonRequestBehavior.DenyGet);
                }
                if (collection["subtype"] == "2")
                {
                    info.Status = 2;
                    bool sucess = bll.UpdateIntentEntryInfoAndNext(info, info.Remark);
                }
                if (collection["ephone"] == "1" && !string.IsNullOrWhiteSpace(info.CustNo))
                {
                    var custInfo = bllCust.GetCustBaseInfo(info.CustNo);
                    bllCust.UpdateCustBaseInfo(custInfo);
                }

                return Json(new { code = success, msg = success ? string.Empty : "保存失败。" }, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);

                return Json(new { code = false, msg = "保存失败。" }, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpPost]
        public ActionResult Commit(Int64 intentId, string remark)
        {
            var info = bll.GetIntentEntryInfoByIntentId(intentId);
            info.Status = 2;
            bool sucess = bll.UpdateIntentEntryInfoAndNext(info, remark);

            return Json(new { code = sucess ? 1 : 0 }, JsonRequestBehavior.DenyGet);
        }

        public ActionResult Details(int intentId)
        {
            var info = bll.GetIntentEntryInfoByIntentId(intentId);
            return View(info);
        }

        public ActionResult Edit(Int64 intentId)
        {
            var info = bll.GetIntentEntryInfoByIntentId(intentId);

            return View(info);
        }

        [HttpPost]
        public ActionResult Edit(IntentEntryInfo info)
        {
            //var info = new IntentEntryInfo();

            //info.IntentId = NumberHelper.StrToInt64(collection["IntentId"]);
            //info.CreateTime = DateTime.Now;
            //info.CustNo = collection["CustNo"];
            //info.OpId = this.EmpId;
            //info.Status = 0;
            //info.Type = 1;
            //info.UpdateTime = DateTime.Now;

            //info.LoanMoney = NumberHelper.RoundToCurrency(NumberHelper.ObjectToDecimal(collection["LoanMoney"]));
            //info.Purpose = collection["Purpose"];
            //info.Rate = NumberHelper.ObjectToDecimal(collection["Rate"]);
            //info.RepaymentType = NumberHelper.ObjectToInt(collection["RepaymentType"], 0);
            //info.Guarantee = collection["Guarantee"] == "1" ? true : false;
            //info.Remark = collection["Remark"];
            //info.Term = NumberHelper.ObjectToInt(collection["Term"]);

            //info.Phone = collection["Phone"];

            try
            {
                // 修改，不可修改客户信息
                if (info.IntentId <= 0)
                {
                    return Json(new { code = false, msg = "意向编号错误。" }, JsonRequestBehavior.DenyGet);
                }
                bool success = bll.UpdateIntentEntryInfo(info);
                if (!success)
                {
                    LogHelper.Info("意向修改保存失败。Id=" + info.IntentId);
                    return Json(new { code = false, msg = "保存失败。" }, JsonRequestBehavior.DenyGet);
                }
                return Json(new { code = success }, JsonRequestBehavior.DenyGet);
            }
            catch
            {
                return Json(new { code = false, msg = "保存失败。" }, JsonRequestBehavior.DenyGet);
            }
        }
        
    }
}
